/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Beans;

import entity.Usuario;
import entity.UsuarioFacade;
import entity.UsuarioFacadeLocal;
import java.io.IOException;
import java.util.List;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.faces.FacesException;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Bryan Valencia
 */
@Named(value = "Usuario")
@RequestScoped
public class UsuarioManagedBean {

    @EJB
    private UsuarioFacadeLocal userFacade = new UsuarioFacade();    
    private List ltUsuarios;
    private entity.Usuario usuario = new Usuario();    
    
    public UsuarioManagedBean() {
        
    }

    public List getLtUsuarios() {
        return ltUsuarios = userFacade.findAll();
    }    

    public Usuario getUsuario() {
        return usuario;
    }

    public void setUsuario(Usuario usuario) {
        this.usuario = usuario;
    }
    
    public String createUser() throws IOException{                   
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        FacesContext ctx = FacesContext.getCurrentInstance();
        ExternalContext extContext = ctx.getExternalContext();
        String ruta = FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();
        String url = extContext.encodeActionURL(ctx.getApplication().getViewHandler().getActionURL(ctx, "/admin/index.xhtml#usuarios-6"));
        //try {
            if(userFacade.find(usuario.getCedula()) == null){
                userFacade.create(usuario);
                session.setAttribute("message", "");
                extContext.redirect(url);
                return "";
                //FacesContext.getCurrentInstance().getExternalContext().redirect("index.xhtml#usuarios-6");
                //String ruta = FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();
                //FacesContext.getCurrentInstance().getExternalContext().redirect(ruta+"/faces/admin/index.xhtml#usuarios-6?faces-redirect=true");
                //return ruta+"/faces/admin/index.xhtml#usuarios-6?faces-redirect=true";
            }else{            
                session.setAttribute("message", "El usuario ya existe.");
                //extContext.redirect(url);
                //return "/index.xhtml#usuarios-6?faces-redirect=true";
                return "";
            }
            
        /*} catch (IOException ioe) {
            throw new FacesException(ioe);
        }*/
        
        
        
    }
       
    
}

